<template>
    <!-- 对话框表单 -->
    <!-- 建议使用 Prettier 格式化代码 -->
    <!-- el-form 内可以混用 el-form-item、FormItem、ba-input 等输入组件 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        width="50%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                <el-form-item  :label="t('device.appsecret')" prop="appsecret">
                                <el-input
                                   :placeholder="t('Please input field', { field: t('device.appsecret') })"
                                        v-model="baTable.form.items!.appsecret"
                                    style="width: 360px" 
                                    readonly
                                ></el-input>
                                <el-button class="margin-left-10" type="primary" @click="generateAppsecret">生成{{t('device.appsecret')}}</el-button>
                </el-form-item>

                <el-form-item :label="t('device.alipay')" prop="alipay">
                               <el-upload action="#" 
                               :show-file-list="false"
                                @change="alipayUpload" list-type="picture-card"  :limit="1"  :auto-upload="false">
                                <el-image fit="cover" :src="fullUrl(baTable.form.items!.alipay)" class="avatar">
                                    <template #error>
                                        <div class="image-slot">
                                            <Icon size="30" color="#c0c4cc" name="el-icon-Picture" />
                                        </div>
                                    </template>
                                </el-image>
                               </el-upload>
                    </el-form-item>

                    <el-form-item :label="t('device.wechat')" prop="wechat">
                               <el-upload action="#" 
                               :show-file-list="false"
                                @change="wechatUpload" list-type="picture-card"  :limit="1"  :auto-upload="false">
                                <el-image fit="cover" :src="fullUrl(baTable.form.items!.wechat)" class="avatar">
                                    <template #error>
                                        <div class="image-slot">
                                            <Icon size="30" color="#c0c4cc" name="el-icon-Picture" />
                                        </div>
                                    </template>
                                </el-image>
                               </el-upload>
                    </el-form-item>
                  
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule,UploadRawFile, UploadUserFile,UploadFiles } from 'element-plus'
import { inject, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'


import { fullUrl } from '/@/utils/common'
import { fileUpload } from '/@/api/common'
import QrCodeDecoder from "qrcode-decoder";
// @ts-ignore
import QRCode from 'qrcode'


const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()
function generateAppsecret() {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let appsecret = '';
    for (let i = 0; i < 32; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        appsecret += characters.charAt(randomIndex);
    }
    baTable.form.items!.appsecret = appsecret;
}

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    appsecret: [buildValidatorData({ name: 'required', title: t('device.appsecret') })],
    heartbeat_time: [buildValidatorData({ name: 'date', title: t('device.heartbeat_time') })],
    create_time: [buildValidatorData({ name: 'date', title: t('device.create_time') })],
})


const qr = new QrCodeDecoder();
const wechatUpload = (file: UploadUserFile, files: UploadFiles) => {    
    upload(file, files).then(res => {
        if (res.code == 1) {    
            baTable.form.items!.wechat = res.data.file.full_url
        }
    })
}

const alipayUpload = (file: UploadUserFile, files: UploadFiles) => {    
    upload(file, files).then(res => {
        if (res.code == 1) {    
            baTable.form.items!.alipay = res.data.file.full_url
        }
    })


}

const upload = (file: UploadUserFile, files: UploadFiles) => {
    // @ts-ignore
    return beforeUpload(file).then(newfile => {
        let fd = new FormData()
        // @ts-ignore
        fd.append('file', newfile)
        return fileUpload(fd)
    })
}


// 将数据 URL 转换为文件
function dataURLtoFile(dataURL: string, filename: string): File {
    const arr = dataURL.split(",");
    const mime = arr[0].match(/:(.*?);/)![1];
    const bstr = atob(arr[1]);
    const u8arr = new Uint8Array(bstr.length);
    for (let i = 0; i < bstr.length; i++) {
        u8arr[i] = bstr.charCodeAt(i);
    }
    return new File([u8arr], filename, { type: mime });
}

const beforeUpload = (file: UploadRawFile) => {
    return new Promise((resolve, reject) => {
        // @ts-ignore
     qr.decodeFromImage(file.url).then((result) => {
        // @ts-ignore
        QRCode.toDataURL(result.data, {
        width: 300, // 设置宽度为 300px
        height: 300, // 设置高度为 300px
        margin: 2, // 设置边距为 2px
        // @ts-ignore
        type: file?.raw?.type,
        color: {
            dark: "#000000", // 二维码前景色（黑色）
            light: "#ffffff", // 二维码背景色（白色）
        },
    }, (err:Error, url:string) => {
            if (err) throw err;
            resolve(dataURLtoFile(url, file.name));
        });
    })
})
}

</script>

<style scoped lang="scss"></style>
